package com.simple.weibo.activity;


import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;

import com.simple.weibo.bean.User;
import com.simple.weibo.database.SimpleDatabase;
import com.simple.weibo.database.SimpleDatabaseHelper;

public class MainActivity extends Activity implements OnClickListener {

    private List<User> userList;
    private ListView listView;
    private Handler handler;

    private ImageButton login;
    private ImageButton add;
    private ImageButton del;
    private ImageButton exit;

    SimpleDatabaseHelper helper;
    ImageAdapter adapter;

    User user = null;
    ProgressDialog dialog;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.main);
        findViews();
        setViews();
    }

    private void findViews() {
        listView = (ListView) findViewById(R.id.listCount);

        login = (ImageButton) findViewById(R.id.loginButton);
        add = (ImageButton) findViewById(R.id.addButton);
        del = (ImageButton) findViewById(R.id.delButton);
        exit = (ImageButton) findViewById(R.id.exitButton);

        dialog = new ProgressDialog(this);
        dialog.setTitle("请稍等...");
    }

    private void setViews() {

        dialog.show();
        checkNetworkStatus();
        login.setOnClickListener(this);
        add.setOnClickListener(this);
        del.setOnClickListener(this);
        exit.setOnClickListener(this);
        listView.setFocusable(true);
        TextView tv = new TextView(this);
        tv.setText("请添加新用户对应用授权");
        tv.setGravity(Gravity.CENTER_HORIZONTAL);
        addContentView(tv, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        listView.setEmptyView(tv);

        listView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                user = userList.get(position);

                if (parent.getTag() != null) {
                    ((View) parent.getTag()).setBackgroundColor(Color.BLACK);
                }
                view.setBackgroundColor(Color.GREEN);
                parent.setTag(view);

            }
        });

        helper = new SimpleDatabaseHelper(MainActivity.this, "mydatabase", null, 1);
        handler = new Handler() {
            public void handleMessage(Message msg) {
                adapter = new ImageAdapter();
                listView.setAdapter(adapter);
                dialog.dismiss();
                super.handleMessage(msg);
            }
        };

    }


    private void checkNetworkStatus() {

        if (!isNetworkAvailable()) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("没有可用的网络，现在去设置？");
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
                }
            });
            builder.setNegativeButton("取消", null);
            builder.show();
        }

    }

    private boolean isNetworkAvailable() {
        boolean isAvailable = false;
        ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo.State gprs = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
        NetworkInfo.State wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
        if (gprs == NetworkInfo.State.CONNECTED || gprs == NetworkInfo.State.CONNECTING
                || wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING) {
            isAvailable = true;
        }
        return isAvailable;
    }

    @Override
    protected void onResume() {
        super.onResume();
        new Thread(new Runnable() {
            public void run() {
                SimpleDatabase db = new SimpleDatabase(helper);
                userList = db.getCountList();
                db.close();
                Message msg = handler.obtainMessage();
                handler.sendMessage(msg);
            }
        }).start();
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.loginButton:
                if (userList.size() > 0) {
                    if (user != null) {
                        if (isNetworkAvailable()) {
                            Intent intent = new Intent();
                            intent.putExtra("userId", user.getUserId());
                            intent.setClass(MainActivity.this, WeiboMainActivity.class);
                            startActivity(intent);
                        } else {
                            Toast.makeText(this, "对不起没有可用的网络", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(this, "请选择需要登录的账号", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(this, "请授权账号后登录", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.addButton:
                if (isNetworkAvailable()) {
                    startActivity(new Intent(this, OAuthActivity.class));
                } else {
                    Toast.makeText(this, "对不起没有可用的网络", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.delButton:
                if (userList.size() > 0) {

                    if (user != null) {

                        AlertDialog.Builder builder = new AlertDialog.Builder(this);
                        builder.setTitle("确认要删除吗?");
                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int which) {
                                SimpleDatabase db = new SimpleDatabase(helper);
                                db.deleteUser(user.getUserId());
                                userList.remove(user);
                                adapter.notifyDataSetChanged();
                                dialog.dismiss();
                            }
                        });
                        builder.setNegativeButton("取消", null);
                        builder.show();

                    } else {
                        Toast.makeText(this, "请选择需要删除的账号", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
            case R.id.exitButton:
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("确认要退出吗?");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        MainActivity.this.finish();
                    }
                });
                builder.setNegativeButton("取消", null);
                builder.show();
                break;
        }
    }


    class ImageAdapter extends BaseAdapter {
        public int getCount() {
            return userList.size();
        }

        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return userList.get(position);
        }

        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(MainActivity.this).inflate(R.layout.list_count, null);
            }
            User user = userList.get(position);
            if (user.getIcon() != null) {
                ImageView iv = (ImageView) convertView.findViewById(R.id.image);
                iv.setImageDrawable(user.getIcon());
            }
            if (user.getUserName() != null) {
                TextView iv = (TextView) convertView.findViewById(R.id.text);
                iv.setText(user.getUserName());
            }
            return convertView;
        }
    }
}